package com.github.iot.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;

import com.github.iot.R;
import com.github.iot.entity.Button;
import com.github.iot.view.switchbutton.FSwitchButton;

import java.util.List;

/**
 * 按钮适配器
 *
 * @Author: 梁声洪
 * @Date: 2019/12/24 22:47
 * @Version: v1.0.0
 */
public class ButtonAdapter extends RecyclerView.Adapter<ButtonAdapter.ButtonViewHolder> {

    private Context context;
    private List<Button> list;
    private View inflater;

    public ButtonAdapter(Context context, List<Button> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public ButtonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        inflater = LayoutInflater.from(context).inflate(R.layout.button_item, parent, false);
        ButtonViewHolder viewHolder = new ButtonViewHolder(inflater);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ButtonViewHolder holder, int position) {
        Button button = list.get(position);
        holder.mName.setText(button.getName());
        holder.mBtnSwitch.setOnCheckedChangeCallback((checked, switchButton) -> {
            mOnCheckedChangeCallback.checkedChange(button, checked);
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class ButtonViewHolder extends RecyclerView.ViewHolder {

        AppCompatTextView mName;
        FSwitchButton mBtnSwitch;

        public ButtonViewHolder(View itemView) {
            super(itemView);
            mName = itemView.findViewById(R.id.tv_button_name);
            mBtnSwitch = itemView.findViewById(R.id.btn_switch);
        }
    }

    /**
     * 声明自定义的接口
     */
    private OnCheckedChangeCallback mOnCheckedChangeCallback;

    /**
     * 定义方法并传给外面的使用者
     *
     * @param callback
     */
    public void setOnCheckedChangeCallback(OnCheckedChangeCallback callback) {
        this.mOnCheckedChangeCallback = callback;
    }

    public interface OnCheckedChangeCallback {

        void checkedChange(Button button, Boolean checked);
    }

}